import re

import pymysql
import requests


def save_book():
    con = pymysql.connect(host="192.168.11.27", port=3306, user="zl", password="123456", database="tadu")
    cur = con.cursor()
    url = "https://www.tadu.com/store"
    res = requests.get(url)
    res = res.content.decode("utf8")
    # print(res)
    # r'<li>.*?<a href="/book/991180/" class="bookImg" target="_blank">.*?<img src="(.*?)" data-src="https://media3.tadu.com//2023/01/26/12/14/c11698a0d9354562811a942c3341916d_a.jpg" />.*?</a>.*?<div class="rtList">.*?<a href="/book/991180/" class="bookNm" target="_blank">(.*?)</a>.*?<a href="/book/991180/" class="bookIntro" target="_blank">(.*?)</a>.*?<div>.*?<a href="javascript:void(0);" class="authorNm" ><i></i>(.*?)</a>.*?<a href="/store/108-a-0-5-a-20-p-1-98" class="classifyLt"><i></i>历史架空</a>.*?<a href="/book/991180/101822295/" class="updateNew" target="_blank"><i></i>(.*?)</a>.*?<div class="condition">.*?<span> 283.3万字</span><hr />.*?<a href="/store/98-t-0-5-a-20-p-1-98">连载</a>.*?</div>.*?</div>.*?</div>.*?</li>',
    books = re.findall(r'<a href=".*?" class="bookImg" target="_blank">.*?<img src=".*?" data-src="(.*?)" />.*?</a>',
                       res, re.S)
    # print(books)
    print(len("https://media3.tadu.com/"))
    for img in books:
        res_mainimage_name = img[24:].replace('/', '_')
        res = requests.get(img)

        # print(res.content)
        b_img = res.content

        with open(f"../media/main_img/{res_mainimage_name}", "wb") as f:
            f.write(b_img)

    # con = pymysql.connect(host="192.168.11.27", port=3306, user="zl", password="123456", database='cartoon')
    # cur = con.cursor()
    # cur.executemany("insert into book_name (name) values (%s)", datas)
    # con.commit()
    # cur.close()
    # con.close()


save_book()
